package com.dragon.modules.yuegou.service.impl.lot;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.entity.lot.ActivityEntity;
import com.dragon.modules.yuegou.entity.lot.ActivityJoinEntity;
import com.dragon.modules.yuegou.entity.member.MemberEntity;
import com.dragon.modules.yuegou.enums.code.ActivityCode;
import com.dragon.modules.yuegou.enums.lot.ActivityProcessStatus;
import com.dragon.modules.yuegou.enums.lot.ActivityPublishStatus;
import com.dragon.modules.yuegou.enums.lot.MemberTicketGetType;
import com.dragon.modules.yuegou.enums.lot.ParticipationStatus;
import com.dragon.modules.yuegou.mapper.lot.ActivityJoinMapper;
import com.dragon.modules.yuegou.model.lot.Activity;
import com.dragon.modules.yuegou.model.lot.ActivityJoin;
import com.dragon.modules.yuegou.model.lot.MemberTicket;
import com.dragon.modules.yuegou.query.lot.ActivityJoinQuery;
import com.dragon.modules.yuegou.query.lot.MemberTicketQuery;
import com.dragon.modules.yuegou.service.lot.ActivityDetailService;
import com.dragon.modules.yuegou.service.lot.ActivityJoinService;
import com.dragon.modules.yuegou.service.lot.ActivityService;
import com.dragon.modules.yuegou.service.lot.MemberTicketService;
import com.dragon.modules.yuegou.service.member.MemberService;
import com.dragon.modules.yuegou.utils.PageToResultUtils;
import com.dragon.modules.yuegou.utils.PrivateStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 会员参与活动信息表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-10-24 10:22:55
 * @version 2.0
 */
@Service("lotActivityJoinService")
public class ActivityJoinServiceImpl extends
		ServiceImpl<ActivityJoinMapper, ActivityJoinEntity> implements ActivityJoinService {

	@Autowired
	private MemberService memberService;

	@Autowired
	private ActivityDetailService activityDetailService;

	@Autowired
	private ActivityService activityService;

	@Autowired
	private MemberTicketService memberTicketService;

	@Override
	public IPage<Activity> participateList(PageRequest page, String busdId, String memberId) {
		IPage<Activity> iPage = baseMapper.participateList(PageToResultUtils.resultToPage(page), busdId, memberId);
		iPage.getRecords().forEach(activity -> {
			if (activity.getProcessStatus().equals(ActivityProcessStatus.PROCESSIONG)) {
				if (activity.getIsDraw()) {
					if (activity.getIsPrize()) {
						activity.setParticipationStatus(ParticipationStatus.HAS_WON);
					} else {
						activity.setParticipationStatus(ParticipationStatus.NOT_WON);
					}
				} else {
					activity.setParticipationStatus(ParticipationStatus.ALREADY_INVOLVED);
				}
			}
		});
		return iPage;
	}

	@Override
	@Transactional
	public ActivityJoin takePart(String activityId, String memberId, String shareId) {
		// 活动状态
		checkActivity(activityId, memberId);

		// 添加会员参与记录
		ActivityJoin activityJoin = new ActivityJoin();
		activityJoin.setMemberId(memberId);
		activityJoin.setActivityId(activityId);
		// 查询会员信息
		MemberEntity member = memberService.getById(memberId);
		activityJoin.memberHeadImg(member.getHeadImg());
		activityJoin.memberNickName(member.getNickName());
		try {
			baseMapper.insert(activityJoin);
		} catch (DuplicateKeyException e) {
			throw new DragonException(ActivityCode.MEMBER_HAS_JOIN);
		}
		// 活动参与人数加1
		activityDetailService.insertJoinMemberNum(activityId);
		// 会员增加一个新劵
		insertMemberTicket(activityId, memberId, activityJoin.getId(), shareId);
		return activityJoin;
	}

	private void checkActivity(String activityId, String memberId) {
		ActivityEntity activity = activityService.getById(activityId);

		// 判断活动是否下架
		if (ActivityPublishStatus.LOWER.equals(activity.getPublishStatus())) {
			throw new DragonException(ActivityCode.ACTIVITY_REMOVED);
		}

		// 判断活动是否开始
		if (LocalDateTime.now().isBefore(activity.getJoinBeginTime())) {
			throw new DragonException(ActivityCode.NOT_STARTED_ENDED);
		}
		if (LocalDateTime.now().isAfter(activity.getJoinEndTime())) {
			throw new DragonException(ActivityCode.NOT_STARTED_ENDED);
		}

		// 判断会员是否参与活动
		ActivityJoinQuery query = new ActivityJoinQuery();
		query.setActivityId(activityId);
		query.setMemberId(memberId);
		ActivityJoinEntity activityJoin = getOne(query.toQueryWrapper());

		if (activityJoin != null) {
			throw new DragonException(ActivityCode.MEMBER_HAS_JOIN);
		}
	}

	private void insertMemberTicket(String activityId, String memberId, String joinId, String shareId) {
		MemberTicket memberTicket = new MemberTicket();
		memberTicket.setMemberId(memberId);
		memberTicket.setActivityId(activityId);
		memberTicket.setJoinId(joinId);
		memberTicket.setTicketCode(PrivateStringUtils.getCode());
		memberTicket.setGetType(MemberTicketGetType.PARTICIPATE);
		memberTicket.setIsPrize(false);
		Boolean b = judgeMaxObtain(activityId, memberId);
		if (Boolean.TRUE.equals(b)) {
			memberTicketService.save(memberTicket);
			// 活动奖券数量加1
			activityDetailService.insertTicketNum(activityId);
			// 查询分享人劵数量是否到达活动单日获取劵数量上限
			MemberTicketQuery query = new MemberTicketQuery();
			query.setActivityId(activityId);
			query.setJoinId(shareId);
			DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			query.createdTime().like(pattern.format(LocalDate.now()));
			Long count = memberTicketService.count(query.toQueryWrapper());
			// 获取活动信息
			ActivityEntity activity = activityService.getById(activityId);
			Integer maxNum = activity.getUserJoinMaxNum();
			if (count < maxNum) {
				// 给分享人发劵
				insertShareTicket(activityId, joinId, shareId);
			}
		}
	}

	private void insertShareTicket(String activityId, String joinId, String shareId) {
		if (StringUtils.isNotEmpty(joinId)) {
			// 获取分享人参与信息
			ActivityJoinEntity activityJoin = getById(joinId);

			if (activityJoin == null) {
				throw new DragonException(ActivityCode.SHARER_DOES_NOT_EXIST);
			}

			MemberTicket memberTicket = new MemberTicket();
			memberTicket.setMemberId(activityJoin.getMemberId());
			memberTicket.setActivityId(activityId);
			memberTicket.setJoinId(joinId);
			memberTicket.setShareId(shareId);
			memberTicket.setTicketCode(PrivateStringUtils.getCode());
			memberTicket.setGetType(MemberTicketGetType.SHARE);
			memberTicket.setIsPrize(false);
			if (judgeMaxObtain(activityId, activityJoin.getMemberId())) {
				memberTicketService.save(memberTicket);
				// 活动奖券数量加1
				activityDetailService.insertTicketNum(activityId);
			}
		}
	}

	private Boolean judgeMaxObtain(String activityId, String memberId) {
		ActivityEntity activity = activityService.getById(activityId);
		Integer num = activity.getUserJoinMaxNum();
		if (num != null && num > 0) {
			MemberTicketQuery query = new MemberTicketQuery();
			query.setActivityId(activityId);
			query.setMemberId(memberId);
			Long count = memberTicketService.count(query.toQueryWrapper());
			return count < num;
		}
		return true;
	}

	@Override
	public void insertShareNum(String joinId) {
		if (StringUtils.isNotEmpty(joinId)) {
			ActivityJoinEntity activityJoin = getById(joinId);
			// 会员分享加1
			baseMapper.insertShareNum(joinId);
			if (StringUtils.isNotEmpty(activityJoin.getActivityId())) {
				activityDetailService.insertShareNum(activityJoin.getActivityId());
			}
		}
	}

}